package com.youlai.rocketmq.producer.tx;


import cn.hutool.core.util.RandomUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author zc
 * @date 2022-10-27 00:56
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class TxProducer {
    @Resource
    RocketMQTemplate rocketMQTemplate;


    public void tx(Boolean isOpenTx) {
        Message<Long> message =  MessageBuilder.withPayload(Long.valueOf(RandomUtil.randomInt(1,1000)))
                // 设置事务Id
                .setHeader(RocketMQHeaders.TRANSACTION_ID,RandomUtil.randomInt(1,1000))
                .build();
        rocketMQTemplate.sendMessageInTransaction("tx:tx_expression", message, isOpenTx);
        log.info("发送事务消息");
    }
}
